<template>
    <div>
        <div class="crumbs">
            <el-breadcrumb separator="/">
                <el-breadcrumb-item>
                    <i class="el-icon-lx-calendar"></i> 秩序册管理
                </el-breadcrumb-item>
            </el-breadcrumb>
        </div>

        <el-card style="text-align: center;" v-show="isAdmin">
            <div class="content-title">支持拖拽</div>
                <el-upload class="upload-demo" action="/api/program/upload" 
                    :headers="headers" show-file-list drag :on-success="uploadSuccess"
                    :on-error="uploadError">
                    <i class="el-icon-upload"></i>
                    <div class="el-upload__text">
                        将文件拖到此处，或
                        <em>点击上传</em>
                    </div>
                    <template #tip>
                        <div class="el-upload__tip">文件大小不超过 1MB  </div>
                    </template>
                </el-upload>
        </el-card>
        
        <el-card style="margin-top: 30px;">
            <el-table :data="tableData" style="width: 100%">
                <el-table-column label="文件名称" prop="fileName" />
                <el-table-column align="left">
                <template #header>
                    <el-input v-model="search" size="small" placeholder="请输入文件名">
                        <template #append>
                            <el-button @click="handleSearch()" icon="el-icon-search">
                                搜索
                            </el-button>
                        </template>
                    </el-input>
                </template>
                <template #default="scope">
                    <el-button size="small" type="primary" icon="el-icon-download"
                        @click="handleDowload(scope.$index, scope.row)">
                        下载
                    </el-button>
                    <el-button size="small" type="danger" v-show="isAdmin" icon="el-icon-delete"
                        @click="handleDelete(scope.$index, scope.row)">删除</el-button>
                </template>
                </el-table-column>
            </el-table>
        </el-card>
        <!-- 分页 -->
        <el-card>
            <el-pagination v-model:currentPage="currentPage" v-model:page-size="pageSize"
                background="true"
                layout="total, prev, pager, next, jumper"
                :total="parseInt(totalNum)" 
                :page-sizes="pageSize"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange" />
        </el-card>
    </div>
</template>

<script>
import { ref,reactive, onMounted, watch } from "vue";
import { useStore } from "vuex";
import { ElMessage, ElMessageBox } from 'element-plus';

export default {
    name: "ruleManage",
    setup() {
        const store = useStore();
        
        const isAdmin = ref(false);
        onMounted(()=>{
            getFileList();
            store.dispatch("CurrentUserInfo").then((res) => {
                    if (res.code === 200) {
                        // console.log("@@@@@@",res.obj.authorities[0].authority);
                        if(res.obj.authorities[0].authority==="ROLE_administrators"){
                            isAdmin.value = true;
                        }
                    } else {
                        console.log(res.message);
                    }
                });
        })  

        const headers = {
            Authorization:localStorage.getItem("token")
        };

        const handleUpload =(item) =>{
            // console.log("item",item);
            mode = item.file;
            // console.log("@文件是",mode);
        }

        //上传文件
        const uploadSuccess = ()=>{
            ElMessage({
                type:"success",
                message:"文件上传成功",
                center:true
            })
            getFileList();
        }
        const uploadError = ()=>{
            ElMessage({
                type:"error",
                message:"文件上传失败",
                center:true
            })
        }

        //搜索文件
        const search = ref('');
        const handleSearch = ()=>{
            store.dispatch("SearchFile",search.value)
            .then(res=>{
                if(res.code===200){
                    tableData.splice(0,tableData.length,...res.obj);
                }else{
                    ElMessage({
                        type:"error",
                        message:"文件不存在",
                        center:true
                    })
                }
            }).catch(err=>{
                console.log("搜索文件异常 ",err)
            })
        }

        //下载文件
        const handleDowload = (index, row) => {
            ElMessageBox.confirm(
                '请使用迅雷下载文件，否则无法正常打开文件',
                '提示',
                {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }
            );
            console.log("下载文件",index, row);
            store.dispatch("DownloadFile",row.fileName)
            .then(res=>{
                const blob = new Blob([res]);
                console.log("blob is ",blob);
                const url = URL.createObjectURL(blob);
                const a = document.createElement('a');
                a.href = url;
                a.download = row.fileName;
                a.click();
                window.URL.revokeObjectURL(url);
            })
        }
        

        //删除文件
        const handleDelete = (index,row)=>{
            store.dispatch("DeleteFile",row.fileName)
            .then(res=>{
                if(res.code===200){
                    ElMessage({
                        type:"success",
                        message:"删除成功",
                        center:true
                    })
                    tableData.splice(index,1);
                }else{
                    ElMessage({
                        type:"error",
                        message:"删除失败",
                        center:true
                    })
                }
            }).catch(err=>{
                console.log("删除文件异常 ",err)
            })
        }

        const tableData = reactive([]);
        const getFileList = ()=>{
            store.dispatch("GetFileList",{
                pageSize:5,
                page:currentPage.value
            }).then(res=>{
                if(res.code===200){
                    totalNum.value = res.obj.records;
                    tableData.splice(0,tableData.length,...res.obj.rows)

                }else{
                    console.log("获取文件失败, ",res.message);
                }
            }).catch(err=>{
                console.log("获取文件异常 ",err)
            })
        }

        //分页
        let currentPage = ref(1);
        let pageSize = ref(5);
        let totalNum = ref();//总条数除以每页显示条数5
        const handleSizeChange = (val) => {
            console.log(`${val} items per page`)
        }
        const handleCurrentChange = (val) => {
            console.log(`current page: ${val}`)
            getFileList();
        }
        return {
            headers,
            isAdmin,
            handleUpload,
            uploadError,
            uploadSuccess,
            handleDelete,
            search,
            handleSearch,
            tableData,
            handleDowload,
            //分页
            currentPage,
            pageSize,
            totalNum,
            handleSizeChange,
            handleCurrentChange,
        };
    },
};
</script>

<style scoped>
.content-title {
    font-weight: 400;
    line-height: 50px;
    margin: 10px 0;
    font-size: 22px;
    color: #1f2f3d;
}

.pre-img {
    width: 100px;
    height: 100px;
    background: #f8f8f8;
    border: 1px solid #eee;
    border-radius: 5px;
}
.crop-demo {
    display: flex;
    align-items: flex-end;
}
.crop-demo-btn {
    position: relative;
    width: 100px;
    height: 40px;
    line-height: 40px;
    padding: 0 20px;
    margin-left: 30px;
    background-color: #409eff;
    color: #fff;
    font-size: 14px;
    border-radius: 4px;
    box-sizing: border-box;
}
.crop-input {
    position: absolute;
    width: 100px;
    height: 40px;
    left: 0;
    top: 0;
    opacity: 0;
    cursor: pointer;
}

.content-download{
    float:right;
    border: 2px solid #eee;
}
</style>